const express=require('express');
const pool=require('../pool')
const r=express.Router();
r.get('/search_cake/:cid',(req,res)=>{
    let category_id=req.params.cid;
    if(!category_id){
        res.send({code:401,msg:"name"});
    }else{
        //查询商品数据
        pool.query('select a.name,a.title,a.price,a.pid,b.product_id,b.sm from product a,product_pic b where a.pid=b.product_id and category_id=?',[category_id],(err,result)=>{
            if(err) throw err;
            if(result.length>0){
                res.send(result);
            }else{
                res.send({code:401,msg:"no found product"});
            }
        })
    }
});
//按分类查询蛋糕
r.get('/tastes_cake/:cname',(req,res)=>{
    let category_name=req.params.cname;
    pool.query('select a.name,a.title,a.price,a.pid,b.sm,b.product_id from product a,product_pic b where a.pid=b.product_id and tastes=?',[category_name],(err,result)=>{
        if(err) throw err;
        if(result.length>0){
            res.send(result);
        }else{
            res.send({code:401,msg:"no found product"})
        }
    });
});
//查询商品详情页的信息
r.get('/detail_pages/:pid',(req,res)=>{
    let _pid=req.params.pid;
    pool.query(`select a.name,a.title,a.meals_num,a.price,a.pid,a.weigth,a.sweetness,b.product_id,b.lg,b.detail_one,b.detail_two,b.detail_three from
        product a,product_pic b where a.pid=b.product_id and a.pid=?`,[_pid],(err,result)=>{
        if(err) throw err;
        if(result.length>0){
            res.send(result);
        }
      });
});
//添加购物车路由
r.get('/add_shopCart/:pid',(req,res)=>{
    let _pid=req.params.pid;
    if(!_pid){
        res.send({code:401,msg:"notFound"})
        return;
    }else{
        pool.query('select count from shoppingcart_item where product_id=?',[_pid],(err,result)=>{
            if(err) throw err;
            if(result.length>0){
                //如果商品数量大于0，在原来基础上加1
                pool.query('update shoppingcart_item set count=count+1 where product_id=?',[_pid],(err,result)=>{
                    if(err) throw err;
                    if(result.affectedRows>0){
                        res.send("1");
                    }else{
                        res.send("0")
                    }
                })
            }else{
                //如果商品数量等于0，添加商品
                pool.query(`INSERT INTO shoppingcart_item(product_id,meals_num) 
                    select pid as product_id,meals_num from product where pid=?`,[_pid],(err,result)=>{
                    if(err) throw err;
                    if(result.affectedRows>0){
                        res.send("1");
                    }else{
                        res.send("0")
                    }
                });
            }
        });
    };
});
module.exports=r;